"""
全局Fixtures和Hooks
"""
import pytest
import json
import os
from pathlib import Path
from common.logger import setup_logging

# 设置日志
setup_logging()


def pytest_configure(config):
    """Pytest配置钩子"""
    # 添加自定义标记
    config.addinivalue_line(
        "markers", "slow: 标记为慢速测试"
    )
    config.addinivalue_line(
        "markers", "integration: 集成测试"
    )
    config.addinivalue_line(
        "markers", "e2e: 端到端测试"
    )
    config.addinivalue_line(
        "markers", "performance: 性能测试"
    )


@pytest.fixture(scope="session")
def test_data_dir():
    """测试数据目录"""
    return Path(__file__).parent / "fixtures" / "data"


@pytest.fixture
def sample_numbers():
    """示例数字列表"""
    return [64, 34, 25, 12, 22, 11, 90]


@pytest.fixture
def sorted_numbers():
    """已排序的数字列表"""
    return [11, 12, 22, 25, 34, 64, 90]


@pytest.fixture
def reverse_sorted_numbers():
    """逆序排列的数字列表"""
    return [90, 64, 34, 25, 22, 12, 11]


@pytest.fixture
def empty_list():
    """空列表"""
    return []


@pytest.fixture
def single_element_list():
    """单元素列表"""
    return [42]


@pytest.fixture
def duplicate_numbers():
    """包含重复数字的列表"""
    return [5, 2, 8, 2, 5, 8, 1]


@pytest.fixture
def negative_numbers():
    """包含负数的列表"""
    return [-3, -1, -7, -2, -5]


@pytest.fixture
def mixed_numbers():
    """正负数混合的列表"""
    return [-5, 10, -3, 7, -1, 15]


@pytest.fixture
def large_dataset():
    """大型数据集"""
    import random
    return [random.randint(1, 1000) for _ in range(1000)]


@pytest.fixture
def user_payloads(test_data_dir):
    """用户测试数据"""
    user_data_file = test_data_dir / "user_payloads.json"
    with open(user_data_file, 'r', encoding='utf-8') as f:
        return json.load(f)


@pytest.fixture(scope="session")
def api_base_url():
    """API基础URL"""
    return os.getenv("TEST_API_BASE_URL", "http://localhost:8000")


@pytest.fixture
def mock_api_response():
    """模拟API响应"""
    def _create_response(status_code=200, data=None, headers=None):
        class MockResponse:
            def __init__(self, status_code, data, headers):
                self.status_code = status_code
                self.data = data or {}
                self.headers = headers or {}
            
            def json(self):
                return self.data
            
            def raise_for_status(self):
                if 400 <= self.status_code < 600:
                    raise Exception(f"HTTP Error: {self.status_code}")
        
        return MockResponse(status_code, data, headers)
    
    return _create_response


@pytest.fixture(autouse=True)
def setup_test_environment():
    """自动设置测试环境"""
    # 设置测试环境变量
    os.environ["ENVIRONMENT"] = "test"
    
    yield
    
    # 测试后清理
    # 可以在这里添加清理逻辑


# Allure报告相关的fixtures
@pytest.fixture
def allure_attach_data():
    """Allure数据附件"""
    def _attach_data(name, data, attachment_type="text/plain"):
        import allure
        allure.attach(str(data), name=name, attachment_type=attachment_type)
    
    return _attach_data